﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Xml;
using JetBlack.Diagnostics;

namespace JetBlack.FeedBus.Distributor.Config
{
    /// <summary>
    /// This class is used by the <see cref="System.Configuration.ConfigurationManager"/>
    /// class to read the application configuarion file.
    /// </summary>
    /// <example>
    /// The following code is an example of a possible app.config file.
    /// <code lang="xml">
    /// &lt;?xml version=&quot;1.0&quot;?&gt;
    /// &lt;configuration&gt;
    ///
    ///  &lt;configSections&gt;
    ///    &lt;section name=&quot;feedBusDistributor&quot; type=&quot;JetBlack.FeedBus.Distributor.Config.Handler, JetBlack.FeedBus&quot;/&gt;
    ///  &lt;/configSections&gt;
    ///
    ///  &lt;feedBusDistributor release=&quot;PRD&quot; debug=&quot;DEV&quot;&gt;
    ///    &lt;add name=&quot;DEV&quot; port=&quot;9123&quot;/&gt;
    ///    &lt;add name=&quot;PRD&quot; port=&quot;9123&quot;/&gt;
    ///  &lt;/feedBusDistributor&gt;
    ///
    ///  &lt;system.diagnostics&gt;
    ///    &lt;trace autoflush=&quot;true&quot;&gt;&lt;/trace&gt;
    ///    &lt;sources&gt;
    ///      &lt;source name=&quot;JetBlack.FeedBus.Distributor&quot; switchName=&quot;DistributorSwitch&quot; /&gt;
    ///    &lt;/sources&gt;
    ///    &lt;switches&gt;
    ///      &lt;add name=&quot;DistributorSwitch&quot; value=&quot;Error&quot;/&gt;
    ///    &lt;/switches&gt;
    ///  &lt;/system.diagnostics&gt;
    ///
    /// &lt;/configuration&gt;
    /// </code>
    /// </example>
    public class Handler : IConfigurationSectionHandler
    {
        private string defaultName = null;
        private Dictionary<string, Adapter> adapters = null;

        /// <summary>
        /// The default configuration name.
        /// </summary>
        public string DefaultName
        {
            get { return defaultName; }
            set { defaultName = value; }
        }

        /// <summary>
        /// Returns the requested named configuration.
        /// </summary>
        /// <param name="name">A configuration name.</param>
        /// <returns>The requested configuration.</returns>
        public Adapter this[string name]
        {
            get
            {
                if (adapters.ContainsKey(name))
                    return adapters[name];
                else
                    return null;
            }
        }

        /// <summary>
        /// Returns the default configuration.
        /// </summary>
        public Adapter DefaultConfig
        {
            get { return this[defaultName]; }
        }

        /// <summary>
        /// The hook into <see cref="System.Configuration.ConfigurationManager"/>
        /// </summary>
        /// <param name="parent">The parent.</param>
        /// <param name="configContext">The config context.</param>
        /// <param name="section">The xml document section.</param>
        /// <returns>The parsed configuration.</returns>
        public object Create(object parent, object configContext, XmlNode section)
        {
            if (section == null)
                return null;

#if DEBUG
            string defaultName = "debug";
#else
            string defaultName = "release";
#endif
            if (section.Attributes[defaultName] == null)
            {
                AppEnvironment.TraceSource.Error("Unable to find configuration default \"{0}\".", defaultName);
                return null;
            }

            this.defaultName = section.Attributes[defaultName].Value;
            if (string.IsNullOrEmpty(this.defaultName))
            {
                AppEnvironment.TraceSource.Error("Unable to determine default configuration for tag \"{0}\"", defaultName);
                return null;
            }

            this.adapters = CreateAdapters(section.SelectNodes("add"));
            if (this.adapters == null || this.adapters.Count == 0)
            {
                AppEnvironment.TraceSource.Error("Unable to read configuration for tag \"add\"");
                return null;
            }

            return this;
        }

        private Dictionary<string, Adapter> CreateAdapters(XmlNodeList xmlNodeList)
        {
            Dictionary<string, Adapter> adapters = new Dictionary<string, Adapter>();

            foreach (XmlElement xmlElement in xmlNodeList)
            {
                Adapter adapter = CreateAdapter(xmlElement);
                if (adapter == null)
                {
                    AppEnvironment.TraceSource.Error("Unable to read configuration for adapters");
                    return null;
                }

                adapters.Add(adapter.Name, adapter);
            }

            return adapters;
        }

        private Adapter CreateAdapter(XmlElement xmlElement)
        {
            string name = xmlElement.GetAttribute("name");
            if (string.IsNullOrEmpty(name))
            {
                AppEnvironment.TraceSource.Error("Unable to read adapter configuration for tag \"name\"");
                return null;
            }

            int port = -1;
            if (!Int32.TryParse(xmlElement.GetAttribute("port"), out port))
            {
                AppEnvironment.TraceSource.Error("Unable to read or understand adapter configuration for tag \"port\"");
                return null;
            }

            return new Adapter(name, port);
        }
    }
}
